﻿Imports System.Drawing
Imports System.Windows.Forms
Imports Spire.DataExport
Imports MySql.Data.MySqlClient

Public Class SuperGrid
    Inherits Windows.Forms.DataGridView

    Public Event OnInserisci(ByVal sender As SuperGrid)
    Public Event OnModifica()
    Public Event OnModificaInGrid(ByVal intRow As Integer, ByVal intCol As Integer, ByRef outProsegui As Boolean, ByRef outInfoInput As InfoInput)
    Public Event OnModificatoOnGrid(ByVal intRow As Integer, ByVal intCol As Integer, ByVal strValoreModificato As String, ByVal intIDModificato As Integer)
    Public Event OnElimina(ByVal sender As SuperGrid)
    Public Event OnRicerca()
    Public Event OnStampa()
    Public Event OnCustomMenuCreating(ByVal outMenu As ContextMenuStrip)

    Public Property NomeElementoPerEsportazione As String
    Public Property ModificaInFinestra As Boolean
        Get
            Return blnModificaInFinestra
        End Get
        Set(ByVal value As Boolean)
            blnModificaInFinestra = value
            If Not blnModificaInFinestra Then
                mnuSwitchModifica.Text = SWITCH_FINESTRA
            Else
                mnuSwitchModifica.Text = SWITCH_GRIGLIA
            End If
            If NomeForm <> "" Then
                SaveSetting(Application.ProductName, "Griglie", NomeForm & Me.Name, ModificaInFinestra)
            End If
        End Set
    End Property
    Public Property NomeForm As String
        Get
            Return strNomeForm
        End Get
        Set(ByVal value As String)
            strNomeForm = value
            ModificaInFinestra = GetSetting(Application.ProductName, "Griglie", strNomeForm & Me.Name, True)
            mnuSwitchModifica.Visible = True
        End Set
    End Property
    Public Property NomeCampoRicercaDaTastiera As String


    Private blnModificaInFinestra As Boolean = True
    Private strNomeForm As String = ""
    Private mnuGrid As ContextMenuStrip
    Private txtModifica As New SuperTextBox
    Private cboModifica As New SuperComboBox
    Private mnuSwitchModifica As New ToolStripMenuItem

    Const SWITCH_GRIGLIA As String = "Attiva modifica in griglia"
    Const SWITCH_FINESTRA As String = "Attiva modifica con finestra"


    Public Enum TipoMenu
        INSERISCI
        MODIFICA
        ELIMINA
        RICERCA
        STAMPA
        VISUALIZZA_COLONNA
        NUMERO_ELEMENTI
        ESPORTA
        SWITCH_MODIFICA
        CUSTOM
        SEPARATOR
    End Enum

    Class InfoMenu
        Public intTipoMenu As TipoMenu
        Public blnEnabledWhenEmpty As Boolean
        Public strCustomNomeMenu As String
        Public imgImage As Image

        Public Sub New(ByVal inTipoMenu As TipoMenu, ByVal inEnabledWhenEmpty As Boolean, Optional ByVal inCustomNomeMenu As String = "", Optional ByVal inImage As Image = Nothing)
            intTipoMenu = inTipoMenu
            blnEnabledWhenEmpty = inEnabledWhenEmpty
            strCustomNomeMenu = inCustomNomeMenu
            imgImage = inImage
        End Sub
    End Class

    Public Enum TipoInput
        NONE
        TESTO
        COMBO
        DATA
        LISTA
    End Enum

    Class InfoInput
        Public intTipo As TipoInput
        Public intMaxLength As Integer
        Public blnOnlyNumber As Boolean
        Public blnIsDecimal As Boolean
        Public blnIsPossibleSpace As Boolean
        Public strQuery As String
        Public strNomeCampo As String
        Public strConnectionString As String
        Public listValori As List(Of GlobalConst)

        Public Sub New(ByVal inTipo As TipoInput, Optional ByVal inMaxLength As Integer = 0, Optional ByVal inOnlyNumber As Boolean = False, Optional ByVal inIsDecimal As Boolean = False, Optional ByVal inIsPossibleSpacing As Boolean = True, Optional ByVal inQuery As String = "", Optional ByVal inNomeCampo As String = "", Optional ByVal inConnectionString As String = "")
            MyBase.New()
            intTipo = inTipo
            intMaxLength = inMaxLength
            blnOnlyNumber = inOnlyNumber
            blnIsDecimal = inIsDecimal
            blnIsPossibleSpace = inIsPossibleSpacing
            strQuery = inQuery
            strNomeCampo = inNomeCampo
            strConnectionString = inConnectionString
            listValori = New List(Of GlobalConst)
        End Sub
    End Class

    Public Sub New()
        MyBase.New()
        mnuGrid = New ContextMenuStrip
        AddHandler mnuGrid.Opening, AddressOf mnuGrid_Opening

        Me.AllowUserToAddRows = False
        Me.AllowUserToDeleteRows = False
        Me.AllowUserToResizeColumns = True
        Me.ReadOnly = True
        Me.StandardTab = True
        Me.BackgroundColor = Color.White
        Me.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
        Me.SelectionMode = DataGridViewSelectionMode.FullRowSelect
        Me.ContextMenuStrip = mnuGrid
        Me.ColumnHeadersDefaultCellStyle.Font = New Font(Me.ColumnHeadersDefaultCellStyle.Font.FontFamily, Me.ColumnHeadersDefaultCellStyle.Font.Size, FontStyle.Bold)
    End Sub

#Region "Metodi Publici"

    Public Sub AddMenuStandard()
        Try
            AddMenu(TipoMenu.INSERISCI)
            AddMenu(TipoMenu.MODIFICA)
            AddMenu(TipoMenu.ELIMINA)
            AddMenu(TipoMenu.SEPARATOR)
            AddMenu(TipoMenu.RICERCA)
            AddMenu(TipoMenu.STAMPA)
            AddMenu(TipoMenu.SEPARATOR)
            AddMenu(TipoMenu.ESPORTA)
            AddMenu(TipoMenu.VISUALIZZA_COLONNA)
            AddMenu(TipoMenu.SWITCH_MODIFICA)
            AddMenu(TipoMenu.SEPARATOR)
            AddMenu(TipoMenu.NUMERO_ELEMENTI)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Public Sub AddMenu(ByRef inListMenu As List(Of InfoMenu))
        Try
            For Each lInfoMenu As InfoMenu In inListMenu
                Call AddMenu(lInfoMenu.intTipoMenu, lInfoMenu.blnEnabledWhenEmpty, lInfoMenu.strCustomNomeMenu, lInfoMenu.imgImage)
            Next
            Call AddingTerminato()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Public Sub SelezionaRow(ByVal inID As Integer)
        Try
            Me.ClearSelection()
            Dim oDataGridViewRow = From row In Me.Rows
                                   Where row.Cells("ID").Value = inID
            Me.CurrentCell = Me.Item(1, CType(oDataGridViewRow(0), DataGridViewRow).Index)
            Me.CurrentRow.Selected = True

        Catch ex As Exception
            Base.ShowError.Show("Seleziona riga", Me.Name, "SelezionaRow", ex)
        End Try
    End Sub

    Public Function GetRowIndex(ByVal inID As Integer, Optional ByVal inNomeCampoID As String = "ID") As Integer
        Try
            Dim oDataGridViewRow = From row In Me.Rows
               Where row.Cells(inNomeCampoID).Value = inID
            Return CType(oDataGridViewRow(0), DataGridViewRow).Index
        Catch ex As Exception
            Base.ShowError.Show("Carica dati", Me.Name, "GetRowIndex", ex)
            Return -1
        End Try
    End Function

    Public Function LoadLayout(ByVal inNomeSezione As String, ByVal inConnectionString As String) As Boolean
        Try
            Dim mnuVisualizzaColonna As ToolStripMenuItem = Nothing
            For Each lMenu As ToolStripItem In mnuGrid.Items
                If lMenu.Name.ToUpper = "mnuVisualizzaColonna1".ToUpper Then
                    mnuVisualizzaColonna = lMenu
                    mnuVisualizzaColonna.Visible = True
                End If
            Next

            Using daAdapt As New MySqlDataAdapter(String.Format("Select * From TabGriglia Where Sezione='{0}' Order by Ordine", inNomeSezione), inConnectionString)
                Using dtTable As New DataTable("TabGriglia")
                    daAdapt.Fill(dtTable)
                    If dtTable.Rows.Count > 0 Then
                        For i As Integer = 0 To dtTable.Rows.Count - 1
                            Me.Columns(dtTable.Rows(i)("NomeColonna").ToString).Visible = CBool(dtTable.Rows(i)("Visible").ToString)
                            If CBool(dtTable.Rows(i)("Visible").ToString) Then
                                Me.Columns(dtTable.Rows(i)("NomeColonna").ToString).DisplayIndex = i + 1
                                Me.Columns(dtTable.Rows(i)("NomeColonna").ToString).Width = CInt(dtTable.Rows(i)("Width").ToString)
                            End If

                            If mnuVisualizzaColonna IsNot Nothing Then
                                Dim lNewMenu As New ToolStripMenuItem
                                lNewMenu.Name = "mnuColonna" & i
                                lNewMenu.Text = dtTable.Rows(i)("NomeColonna").ToString
                                lNewMenu.Image = Nothing
                                lNewMenu.CheckOnClick = True
                                lNewMenu.Checked = CBool(dtTable.Rows(i)("Visible").ToString)
                                AddHandler lNewMenu.Click, AddressOf ColVisibleChange
                                mnuVisualizzaColonna.DropDownItems.Add(lNewMenu)
                                lNewMenu = Nothing
                            End If
                        Next
                    Else
                        mnuVisualizzaColonna.Visible = False
                    End If
                End Using
            End Using
            Return True
        Catch ex As Exception
            Base.ShowError.Show("Carica Griglia", Me.Name, "LoadLayout", ex)
            Return False
        End Try
    End Function

    Public Function SaveLayout(ByVal inNomeSezione As String, ByVal inConnectionString As String) As Boolean
        Try
            If Me.Columns.Count = 0 Then Return True
            Using daAdapt As New MySqlDataAdapter(String.Format("Select * From TabGriglia Where Sezione='{0}' Order by Ordine", inNomeSezione), inConnectionString)
                Using dtTable As New DataTable("TabGriglia")
                    daAdapt.Fill(dtTable)
                    If dtTable.Rows.Count > 0 Then
                        For Each lRow As DataRow In dtTable.Rows
                            lRow("Ordine") = Me.Columns(lRow("NomeColonna").ToString).DisplayIndex
                            lRow("Width") = Me.Columns(lRow("NomeColonna").ToString).Width
                            lRow("Visible") = Me.Columns(lRow("NomeColonna").ToString).Visible
                        Next

                        Using cmCommand As New MySqlCommandBuilder(daAdapt)
                            daAdapt.Update(dtTable)
                        End Using
                    End If
                End Using
            End Using

            Return True
        Catch ex As Exception
            Base.ShowError.Show("Carica Griglia", Me.Name, "SaveLayout", ex)
            Return False
        End Try
    End Function

#End Region

#Region "Metodi Privati"

    Private Sub AddingTerminato()
        Try
            RaiseEvent OnCustomMenuCreating(mnuGrid)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub AddMenu(ByVal inTipoMenu As TipoMenu, Optional ByVal inEnabledWhenEmpty As Boolean = False, Optional ByVal inCustomNomeMenu As String = "", Optional ByVal inCustomPicture As System.Drawing.Image = Nothing)
        Try
            Dim lNewMenu As New ToolStripMenuItem
            Select Case inTipoMenu
                Case TipoMenu.INSERISCI
                    lNewMenu.Name = "mnuInserisci" & 1
                    lNewMenu.Text = "Inserisci elemento"
                    lNewMenu.Image = My.Resources.imgNew16
                    AddHandler lNewMenu.Click, AddressOf Inserisci
                    mnuGrid.Items.Add(lNewMenu)
                Case TipoMenu.MODIFICA
                    lNewMenu.Name = "mnuModifica" & 0
                    lNewMenu.Text = "Modifica elemento"
                    lNewMenu.Image = My.Resources.imgModify16
                    AddHandler lNewMenu.Click, AddressOf Modifica
                    mnuGrid.Items.Add(lNewMenu)
                Case TipoMenu.ELIMINA
                    lNewMenu.Name = "mnuElimina" & 0
                    lNewMenu.Text = "Elimina elemento"
                    lNewMenu.Image = My.Resources.imgDelete16
                    AddHandler lNewMenu.Click, AddressOf Elimina
                    mnuGrid.Items.Add(lNewMenu)
                Case TipoMenu.RICERCA
                    lNewMenu.Name = "mnuRicerca" & 1
                    lNewMenu.Text = "Ricerca elemento"
                    lNewMenu.Image = My.Resources.imgSearch16
                    AddHandler lNewMenu.Click, AddressOf Ricerca
                    mnuGrid.Items.Add(lNewMenu)
                Case TipoMenu.STAMPA
                    lNewMenu.Name = "mnuStampa" & 0
                    lNewMenu.Text = "Stampa"
                    lNewMenu.Image = My.Resources.imgPrint16
                    AddHandler lNewMenu.Click, AddressOf Stampa
                    mnuGrid.Items.Add(lNewMenu)
                Case TipoMenu.VISUALIZZA_COLONNA
                    lNewMenu.Name = "mnuVisualizzaColonna" & 1
                    lNewMenu.Text = "Visualizza Colonna"
                    lNewMenu.Image = My.Resources.imgVisualizzaColonna16
                    lNewMenu.Visible = False
                    mnuGrid.Items.Add(lNewMenu)
                Case TipoMenu.NUMERO_ELEMENTI
                    lNewMenu.Name = "mnuNumeroElementi"
                    lNewMenu.Text = ""
                    lNewMenu.Image = Nothing
                    mnuGrid.Items.Add(lNewMenu)
                Case TipoMenu.ESPORTA
                    Dim lMenuEsporta As New ToolStripMenuItem
                    lMenuEsporta.Name = "mnuEsporta" & 0
                    lMenuEsporta.Text = "Esporta"
                    lMenuEsporta.Image = Nothing
                    mnuGrid.Items.Add(lMenuEsporta)

                    Dim lMenuSottoEsporta As New ToolStripMenuItem
                    lMenuSottoEsporta.Name = "mnuEsportaPDF"
                    lMenuSottoEsporta.Text = "File PDF"
                    lMenuSottoEsporta.Image = My.Resources.imgPdf16
                    lMenuEsporta.DropDownItems.Add(lMenuSottoEsporta)
                    AddHandler lMenuSottoEsporta.Click, AddressOf Esporta
                    lMenuSottoEsporta = Nothing

                    lMenuSottoEsporta = New ToolStripMenuItem
                    lMenuSottoEsporta.Name = "mnuEsportaTesto"
                    lMenuSottoEsporta.Text = "File di testo"
                    lMenuSottoEsporta.Image = My.Resources.imgText16
                    lMenuEsporta.DropDownItems.Add(lMenuSottoEsporta)
                    AddHandler lMenuSottoEsporta.Click, AddressOf Esporta
                    lMenuSottoEsporta = Nothing

                    lMenuSottoEsporta = New ToolStripMenuItem
                    lMenuSottoEsporta.Name = "mnuEsportaExcel"
                    lMenuSottoEsporta.Text = "File Excel"
                    lMenuSottoEsporta.Image = My.Resources.imgExcel16
                    lMenuEsporta.DropDownItems.Add(lMenuSottoEsporta)
                    AddHandler lMenuSottoEsporta.Click, AddressOf Esporta
                    lMenuSottoEsporta = Nothing

                    lMenuSottoEsporta = New ToolStripMenuItem
                    lMenuSottoEsporta.Name = "mnuEsportaCSV"
                    lMenuSottoEsporta.Text = "File CSV"
                    lMenuSottoEsporta.Image = My.Resources.imgText16
                    lMenuEsporta.DropDownItems.Add(lMenuSottoEsporta)
                    AddHandler lMenuSottoEsporta.Click, AddressOf Esporta
                    lMenuSottoEsporta = Nothing

                    lMenuSottoEsporta = New ToolStripMenuItem
                    lMenuSottoEsporta.Name = "mnuEsportaRTF"
                    lMenuSottoEsporta.Text = "File RTF"
                    lMenuSottoEsporta.Image = My.Resources.imgWord15
                    lMenuEsporta.DropDownItems.Add(lMenuSottoEsporta)
                    AddHandler lMenuSottoEsporta.Click, AddressOf Esporta
                    lMenuSottoEsporta = Nothing

                    lMenuSottoEsporta = New ToolStripMenuItem
                    lMenuSottoEsporta.Name = "mnuEsportaXML"
                    lMenuSottoEsporta.Text = "File XML"
                    lMenuSottoEsporta.Image = My.Resources.imgXML16
                    lMenuEsporta.DropDownItems.Add(lMenuSottoEsporta)
                    AddHandler lMenuSottoEsporta.Click, AddressOf Esporta
                    lMenuSottoEsporta = Nothing

                    lMenuSottoEsporta = New ToolStripMenuItem
                    lMenuSottoEsporta.Name = "mnuEsportaHTML"
                    lMenuSottoEsporta.Text = "File HTML"
                    lMenuSottoEsporta.Image = My.Resources.imgHtml16
                    lMenuEsporta.DropDownItems.Add(lMenuSottoEsporta)
                    AddHandler lMenuSottoEsporta.Click, AddressOf Esporta
                    lMenuSottoEsporta = Nothing

                    lMenuEsporta = Nothing
                Case TipoMenu.CUSTOM
                    lNewMenu.Name = "mnuCustom" & mnuGrid.Items.Count & "_" & CInt(inEnabledWhenEmpty)
                    lNewMenu.Text = inCustomNomeMenu
                    lNewMenu.Image = inCustomPicture
                    mnuGrid.Items.Add(lNewMenu)
                Case TipoMenu.SWITCH_MODIFICA
                    lNewMenu.Name = "mnuSwitch" & 0
                    lNewMenu.Text = SWITCH_GRIGLIA
                    lNewMenu.Image = My.Resources.imgSwitchModifica16
                    lNewMenu.Visible = False
                    AddHandler lNewMenu.Click, AddressOf SwitchModifica
                    mnuGrid.Items.Add(lNewMenu)
                    mnuSwitchModifica = lNewMenu
                Case TipoMenu.SEPARATOR
                    Dim lNewSep As New ToolStripSeparator
                    lNewSep.Name = "mnuSep" & mnuGrid.Items.Count
                    mnuGrid.Items.Add(lNewSep)
                    lNewSep = Nothing
            End Select

            lNewMenu = Nothing
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub ColVisibleChange(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            Dim lMenu As ToolStripMenuItem = CType(sender, ToolStripMenuItem)

            Me.Columns(lMenu.Text).Visible = lMenu.Checked
        Catch ex As Exception
            Base.ShowError.Show("Carica Griglia", Me.Name, "ColVisibleChange", ex)
        End Try
    End Sub

    Private Sub ModificaInGrid(ByVal intRow As Integer, ByVal intCol As Integer)
        Try
            Dim oInfoInput As New InfoInput(TipoInput.TESTO)
            Dim blnProsegui As Boolean = False
            Dim strValore As String = ""

            RaiseEvent OnModificaInGrid(intRow, intCol, blnProsegui, oInfoInput)
            If blnProsegui Then
                Select Case oInfoInput.intTipo
                    Case TipoInput.TESTO
                        txtModifica = New SuperTextBox
                        txtModifica.Name = "txtModifica"
                        txtModifica.Tag = intCol & ";" & intRow
                        txtModifica.Text = Me.Rows(intRow).Cells(intCol).Value.ToString
                        txtModifica.MaxLength = oInfoInput.intMaxLength
                        txtModifica.OnlyNumber = oInfoInput.blnOnlyNumber
                        txtModifica.IsDecimal = oInfoInput.blnIsDecimal
                        txtModifica.IsPossibleSpacing = oInfoInput.blnIsPossibleSpace
                        txtModifica.Left = Me.GetCellDisplayRectangle(intCol, intRow, True).Left + Me.Left
                        txtModifica.Top = Me.GetCellDisplayRectangle(intCol, intRow, True).Top + Me.Top
                        txtModifica.Size = Me.GetCellDisplayRectangle(intCol, intRow, True).Size
                        txtModifica.Parent = Me.Parent
                        txtModifica.BringToFront()
                        txtModifica.SetFocusSelected()
                        AddHandler txtModifica.LostFocus, AddressOf txtModifica_LostFocus
                        AddHandler txtModifica.KeyDown, AddressOf txtModifica_KeyDown
                    Case TipoInput.COMBO
                        cboModifica = New SuperComboBox
                        cboModifica.Name = "cboModifica" & ";" & intCol & ";" & intRow
                        cboModifica.Left = Me.GetCellDisplayRectangle(intCol, intRow, True).Left + Me.Left
                        cboModifica.Top = Me.GetCellDisplayRectangle(intCol, intRow, True).Top + Me.Top
                        cboModifica.Size = Me.GetCellDisplayRectangle(intCol, intRow, True).Size
                        cboModifica.Parent = Me.Parent
                        cboModifica.BringToFront()
                        cboModifica.Focus()
                        cboModifica.Load(oInfoInput.strQuery, oInfoInput.strNomeCampo, oInfoInput.strConnectionString)
                        cboModifica.SelectedIndex = cboModifica.FindString(Me.Rows(intRow).Cells(intCol).Value.ToString)
                        AddHandler cboModifica.LostFocus, AddressOf cboModifica_LostFocus
                        AddHandler cboModifica.SelectedIndexChanged, AddressOf cboModifica_LostFocus
                        AddHandler cboModifica.KeyDown, AddressOf cboModifica_KeyDown
                    Case TipoInput.LISTA
                        Dim strTestoCorrente As String = Me.Rows(intRow).Cells(intCol).Value.ToString
                        Dim intPosizione As Integer = oInfoInput.listValori.FindIndex(Function(value As GlobalConst)
                                                                                          Return value.Name = strTestoCorrente
                                                                                      End Function)
                        If intPosizione = oInfoInput.listValori.Count - 1 Then
                            intPosizione = 0
                        Else
                            intPosizione += 1
                        End If
                        RaiseEvent OnModificatoOnGrid(intRow, intCol, oInfoInput.listValori.Item(intPosizione).Name, oInfoInput.listValori.Item(intPosizione).Number)
                    Case TipoInput.DATA
                        Dim ofrmCalendario As New frmCalendar
                        If ofrmCalendario.ShowDialog = Windows.Forms.DialogResult.OK Then
                            strValore = ofrmCalendario.strData
                        Else
                            Return
                        End If
                        ofrmCalendario = Nothing
                        RaiseEvent OnModificatoOnGrid(intRow, intCol, strValore, 0)
                End Select
            End If
            oInfoInput = Nothing
        Catch ex As Exception
            Base.ShowError.Show("Modifica Dati", Me.Name, "ModificaInGrid", ex)
        End Try
    End Sub

    Private Sub txtModifica_LostFocus()
        Try
            If txtModifica Is Nothing Then Return

            Dim vett() As Object = Split(txtModifica.Tag, ";")
            Dim intRow As Integer = vett(1)
            Dim intCol As Integer = vett(0)

            If txtModifica.Text.ToUpper <> Me.Rows(intRow).Cells(intCol).Value.ToString.ToUpper Then
                RaiseEvent OnModificatoOnGrid(intRow, intCol, txtModifica.Text, 0)
            End If
        Catch ex As Exception
            Base.ShowError.Show("Modifica Dati", Me.Name, "txtModifica_LostFocus", ex)
        Finally
            If txtModifica IsNot Nothing Then
                txtModifica.Visible = False
                txtModifica.Dispose()
            End If
        End Try
    End Sub

    Private Sub cboModifica_LostFocus()
        Try
            If cboModifica Is Nothing Then Return

            Dim vett() As Object = Split(cboModifica.Name, ";")
            Dim intRow As Integer = vett(2)
            Dim intCol As Integer = vett(1)

            If cboModifica.Text.ToUpper <> Me.Rows(intRow).Cells(intCol).Value.ToString.ToUpper Then
                RaiseEvent OnModificatoOnGrid(intRow, intCol, cboModifica.Text, cboModifica.SelectedValue)
            End If
        Catch ex As Exception
            Base.ShowError.Show("Modifica Dati", Me.Name, "cboModifica_LostFocus", ex)
        Finally
            If cboModifica IsNot Nothing AndAlso cboModifica.Text.ToUpper <> "" Then
                cboModifica.Visible = False
                cboModifica = Nothing
            End If
        End Try
    End Sub

    Private Sub cboModifica_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Escape And e.KeyCode = Keys.Return Then
            Call cboModifica_LostFocus()
        End If
    End Sub

    Private Sub txtModifica_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Escape And e.KeyCode = Keys.Return Then
            Call txtModifica_LostFocus()
        End If
    End Sub

    Private Sub SwitchModifica()
        ModificaInFinestra = Not ModificaInFinestra
    End Sub

    Private Sub ScorriGriglia(ByVal inLettera As String)
        Try
            Dim i As Integer = 0
            If Me.Rows.Count = 1 Then Return
            If Me.CurrentRow Is Nothing OrElse Me.CurrentRow.Index = Me.Rows.Count - 1 Then
                i = 0
            Else
                i = Me.CurrentRow.Index + 1
            End If
            Do
                If Me.Rows(i).Cells(NomeCampoRicercaDaTastiera).Value.ToString.Substring(0, 1).ToUpper = inLettera.ToUpper Then
                    For k As Integer = 0 To Me.Columns.Count - 1
                        If Me.Columns(k).Visible Then
                            Me.FirstDisplayedScrollingRowIndex = i
                            Me.FirstDisplayedScrollingColumnIndex = k
                            Me.CurrentCell = Me(k, i)
                            Me.Refresh()
                            Return
                        End If
                    Next
                    Return
                End If
                If i = Me.Rows.Count - 1 Then
                    i = 0
                Else
                    i = i + 1
                End If
            Loop Until i = Me.CurrentRow.Index
        Catch ex As Exception
            Base.ShowError.Show("Scorri Griglia", Me.Name, "ScorriGriglia", ex)
        End Try
    End Sub

#End Region

#Region "Eventi"

    Private Sub Inserisci()
        Try
            RaiseEvent OnInserisci(Me)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub Modifica()
        Try
            RaiseEvent OnModifica()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub Elimina()
        Try
            RaiseEvent OnElimina(Me)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub Ricerca()
        Try
            RaiseEvent OnRicerca()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub Stampa()
        Try
            RaiseEvent OnStampa()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

#End Region

#Region "Esportazione"

    Private Sub Esporta(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            Dim strNomeFile As String = ""
            Dim dtTable As DataTable = CType(Me.DataSource, DataTable)
            Dim blnFine As Boolean = False

            Do While blnFine = False
                blnFine = True
                For Each lCol As DataGridViewColumn In Me.Columns
                    If lCol.Visible = False Then
                        dtTable.Columns.Remove(lCol.DataPropertyName)
                        blnFine = False
                        Exit For
                    End If
                Next
            Loop

            Dim strEstensione As String = ""
            Dim oSaveFileDialog As New SaveFileDialog
            Select Case CType(sender, ToolStripMenuItem).Name
                Case "mnuEsportaHTML" : strEstensione = "htm"
                Case "mnuEsportaXML" : strEstensione = "xml"
                Case "mnuEsportaRTF" : strEstensione = "rtf"
                Case "mnuEsportaPDF" : strEstensione = "pdf"
                Case "mnuEsportaCSV" : strEstensione = "csv"
                Case "mnuEsportaExcel" : strEstensione = "xls"
                Case "mnuEsportaTesto" : strEstensione = "txt"
            End Select

            strNomeFile = NomeElementoPerEsportazione & "." & strEstensione
            oSaveFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
            oSaveFileDialog.FileName = strNomeFile
            oSaveFileDialog.Filter = "File " & strEstensione & "|*." & strEstensione
            If oSaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
                strNomeFile = IIf(strNomeFile.EndsWith("." & strEstensione), oSaveFileDialog.FileName, oSaveFileDialog.FileName & "." & strEstensione)
                Select Case CType(sender, ToolStripMenuItem).Name
                    Case "mnuEsportaHTML" : Call EsportaHTML(strNomeFile, dtTable)
                    Case "mnuEsportaXML" : Call EsportaXML(strNomeFile, dtTable)
                    Case "mnuEsportaRTF" : Call EsportaRFT(strNomeFile, dtTable)
                    Case "mnuEsportaPDF" : Call EsportaPDF(strNomeFile, dtTable)
                    Case "mnuEsportaCSV" : Call EsportaCSV(strNomeFile, dtTable)
                    Case "mnuEsportaExcel" : Call EsportaExcel(strNomeFile, dtTable)
                    Case "mnuEsportaTesto" : Call EsportaTxt(strNomeFile, dtTable)
                End Select
            End If

            oSaveFileDialog = Nothing
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub EsportaXML(ByVal inFileName As String, ByRef dtTable As DataTable)
        Try
            Dim oXMLExport As New Spire.DataExport.XML.XMLExport

            oXMLExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable
            oXMLExport.DataTable = dtTable
            oXMLExport.FileName = inFileName
            oXMLExport.SaveToFile()

            oXMLExport = Nothing
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub EsportaRFT(ByVal inFileName As String, ByRef dtTable As DataTable)
        Try
            Dim oRTFExport As New Spire.DataExport.RTF.RTFExport

            oRTFExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable
            oRTFExport.DataTable = dtTable
            oRTFExport.FileName = inFileName
            oRTFExport.SaveToFile()

            oRTFExport = Nothing
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub EsportaHTML(ByVal inFileName As String, ByRef dtTable As DataTable)
        Try
            Dim oHTMLExport As New Spire.DataExport.HTML.HTMLExport

            oHTMLExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable
            oHTMLExport.DataTable = dtTable
            oHTMLExport.SaveToFile(inFileName)

            oHTMLExport = Nothing
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub EsportaTxt(ByVal inFileName As String, ByRef dtTable As DataTable)
        Try
            Dim oTXTExport As New Spire.DataExport.TXT.TXTExport

            oTXTExport.ExportType = TXT.TextExportType.TXT
            oTXTExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable
            oTXTExport.DataTable = dtTable
            oTXTExport.SaveToFile(inFileName)

            oTXTExport = Nothing
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub EsportaCSV(ByVal inFileName As String, ByRef dtTable As DataTable)
        Try
            Dim oTXTExport As New Spire.DataExport.TXT.TXTExport

            oTXTExport.ExportType = TXT.TextExportType.CSV
            oTXTExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable
            oTXTExport.DataTable = dtTable
            oTXTExport.SaveToFile(inFileName)

            oTXTExport = Nothing
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub EsportaExcel(ByVal inFileName As String, ByRef dtTable As DataTable)
        Try
            Dim oCellExport As New Spire.DataExport.XLS.CellExport

            oCellExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable
            oCellExport.DataTable = dtTable
            oCellExport.SaveToFile(inFileName)

            oCellExport = Nothing
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub EsportaPDF(ByVal inFileName As String, ByRef dtTable As DataTable)
        Try
            Dim oPDFExport As New Spire.DataExport.PDF.PDFExport

            oPDFExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable
            oPDFExport.DataTable = dtTable
            oPDFExport.SaveToFile(inFileName)

            oPDFExport = Nothing
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub


#End Region

#Region "Eventi Griglia"

    Private Sub mnuGrid_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
        Try
            For Each lMenu As ToolStripItem In mnuGrid.Items
                Dim strEnabled As String = lMenu.Name.Substring(lMenu.Name.Length - 1, 1)
                If IsNumeric(strEnabled) Then
                    If CBool(strEnabled) Then
                        lMenu.Enabled = True
                    Else
                        If Me.Rows.Count = 0 Then
                            lMenu.Enabled = False
                        Else
                            lMenu.Enabled = True
                        End If
                    End If
                End If
            Next
            For Each lMenu As ToolStripItem In mnuGrid.Items
                If lMenu.Name.ToUpper = "mnuNumeroElementi".ToUpper Then
                    lMenu.Text = "Numero elementi: " & Me.Rows.Count
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub grdDati_CellContentDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles Me.CellDoubleClick
        Try
            If ModificaInFinestra Then
                RaiseEvent OnModifica()
            Else
                Call ModificaInGrid(e.RowIndex, e.ColumnIndex)
            End If
        Catch ex As Exception
            Base.ShowError.Show("Seleziona riga", Me.Name, "grdDati_CellContentDoubleClick", ex)
        End Try
    End Sub

    Private Sub SuperGrid_DataBindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles Me.DataBindingComplete
        Try
            For Each lCol As DataGridViewColumn In Me.Columns
                If lCol.ValueType = GetType(Integer) Or lCol.ValueType = GetType(Single) Or lCol.ValueType = GetType(Decimal) Or lCol.ValueType = GetType(Double) Or lCol.ValueType = GetType(Int16) Or lCol.ValueType = GetType(Int32) Or lCol.ValueType = GetType(Int64) Then
                    lCol.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                End If
            Next
        Catch ex As Exception
            Base.ShowError.Show("Allineamento", Me.Name, "SuperGrid_DataBindingComplete", ex)
        End Try
    End Sub

    Private Sub SuperGrid_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.DoubleClick
        Try
            If Me.CurrentRow Is Nothing Then
                RaiseEvent OnInserisci(Me)
            End If
        Catch ex As Exception
            Base.ShowError.Show("Seleziona riga", Me.Name, "SuperGrid_MouseDown", ex)
        End Try
    End Sub

    Private Sub grdDati_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Try
            If e.KeyCode = Keys.Return Then
                If ModificaInFinestra Then
                    RaiseEvent OnModifica()
                Else
                    Call ModificaInGrid(Me.CurrentCell.RowIndex, Me.CurrentCell.ColumnIndex)
                End If
                'ElseIf e.KeyCode = Keys.Tab Then
                '    Me.Parent.SelectNextControl(Me, True, True, True, True)
            ElseIf (e.KeyCode > Keys.A And e.KeyCode < Keys.Z) Or (e.KeyCode > Keys.D0 And e.KeyCode < Keys.D9) Then
                If NomeCampoRicercaDaTastiera <> "" Then
                    Call ScorriGriglia(Chr(e.KeyData))
                End If
            End If
        Catch ex As Exception
            Base.ShowError.Show("Seleziona riga", Me.Name, "grdDati_KeyDown", ex)
        End Try
    End Sub

    Private Sub SuperGrid_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
        Try
            Dim oHitTestInfo As DataGridView.HitTestInfo = Me.HitTest(e.X, e.Y)
            If oHitTestInfo.Type = DataGridViewHitTestType.None Then
                Me.ClearSelection()
                Me.CurrentCell = Nothing
            End If
        Catch ex As Exception
            Base.ShowError.Show("Seleziona riga", Me.Name, "SuperGrid_MouseDown", ex)
        End Try
    End Sub

#End Region

End Class
